package com.admin.utils;

import com.admin.business.config.oss.OSSUtil;
import com.tiangong.framework.bo.CDO;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import javax.swing.*;
import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FileExportImportUtil {

    InputStream os;
    List<List<String>> list = new ArrayList<List<String>>();

    //创建工作本
    public HSSFWorkbook demoWorkBook = new HSSFWorkbook();
    //创建表
    public HSSFSheet demoSheet = demoWorkBook.createSheet("Sheet1");

    /**
     * 创建行
     *
     * @param cells
     * @param rowIndex
     */
    public void createTableRow(List<String> cells, int rowIndex) {
        //创建第rowIndex行
        Row row = demoSheet.createRow(rowIndex);
        for (int i = 0; i < cells.size(); i++) {
            //创建第i个单元格
            Cell cell = row.createCell(i);
            cell.setCellValue(cells.get(i));
        }
    }

    /**
     * 创建整个Excel表
     *
     * @throws SQLException
     */
    public void createExcelSheet() throws SQLException {
        for (int i = 0; i < list.size(); i++) {
            createTableRow((List<String>) list.get(i), i);
        }
    }

    /**
     * 导出表格
     *
     * @param sheet
     * @throws IOException
     */
    public InputStream exportExcel(HSSFSheet sheet) throws IOException {
        sheet.setGridsPrinted(true);
        HSSFFooter footer = sheet.getFooter();
        footer.setRight("Page " + HSSFFooter.page() + " of " +
                HSSFFooter.numPages());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            demoWorkBook.write(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] ba = baos.toByteArray();
        os = new ByteArrayInputStream(ba);
        return os;
    }


    public InputStream export(List<List<String>> zlist) {
        InputStream myos = null;
        try {
            list = zlist;
            createExcelSheet();
            myos = exportExcel(demoSheet);
            return myos;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "表格导出出错，错误信息 ：" + e + "\n错误原因可能是表格已经打开。");
            e.printStackTrace();
            return null;
        } finally {
            try {
                os.close();
                if (myos != null) myos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public HSSFWorkbook getHSSFWorkbook(List<List<String>> zlist) {
        try {
            list = zlist;
            createExcelSheet();
            //myos= exportExcel(demoSheet);
            demoSheet.setGridsPrinted(true);
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " +
                    HSSFFooter.numPages());
            return demoWorkBook;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "表格导出出错，错误信息 ：" + e + "\n错误原因可能是表格已经打开。");
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 创建多文件压缩包
     *
     * @param dir     文件路径
     * @param srcFile 文件file集合
     * @param expName 文件名
     */
    public static void createRar(String dir, List<File> srcFile, String expName) {

        if (!new File(dir).exists()) {//检测生成路径
            new File(dir).mkdirs();
        }
        File zipfile = new File(dir + "/" + expName + ".rar");
        FileUtils.deleteFile(zipfile);//删除之前的压缩文件
        FileExportImportUtil.zipFiles(srcFile, zipfile);//生成压缩文件
        for (int i = 1; i <= srcFile.size(); i++) {//删除之前的xls
            FileUtils.deleteFile(new File(dir + "/" + expName + "_" + i + ".xls"));
        }

        try {

            InputStream fis = new BufferedInputStream(new FileInputStream(zipfile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 创建excel
     *
     * @param headName 表头
     * @param list     数据字符串集合
     * @param expName  文件名
     * @param dir      文件路径
     * @return
     * @throws Exception
     */
    public static File createExcel(String[] headName, List<List<String>> list, String expName, String dir) throws Exception {
        // 格式化时间
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet1");
        // 创建表头
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        for (int y = 0; y < headName.length; y++) {//循环表头信息
            cell = row.createCell(y);
            cell.setCellValue(headName[y]);
        }
        for (int x = 0; x < list.size(); x++) {//循环数据信息
            row = sheet.createRow(x + 1);
            List<String> rowString = list.get(x);
            for (int i = 0; i < rowString.size(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(rowString.get(i));
            }
        }
        FileUtils.deleteFile(dir + "/" + expName + ".xlsx");
        new File(dir).mkdirs();
        String filePath = dir + "/" + expName + ".xlsx";
        File file = noExists(filePath);

        FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();
        return file;
    }

    public static File noExists(String filePath) {
        File file = new File(filePath);
        int i = 1;
        while (file.exists()) {
            file = new File(filePath.split("\\.")[0] + "（" + i + "）." + filePath.split("\\.")[1]);
            i++;
        }
        return file;
    }

    /**
     * 压缩文件
     *
     * @param srcfile File[] 需要压缩的文件列表
     * @param zipfile File 压缩后的文件
     */
    public static void zipFiles(List<File> srcfile, File zipfile) {
        byte[] buf = new byte[1024];
        String ZIP_ENCODEING = "GBK";
        try {
            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
            out.setEncoding(ZIP_ENCODEING);
            for (int i = 0; i < srcfile.size(); i++) {
                File file = srcfile.get(i);
                FileInputStream in = new FileInputStream(file);
                out.putNextEntry(new ZipEntry(file.getName()));
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String uploadSupportingOfficerFile(List<CDO> list, String time, String SecondedName) throws IOException {
        //String[] titles = {"序列", "姓名", "电话", "楼宇", "面积", "单位", "民族", "政治面貌", "个人宣言", "人员同意状态"};
        String[] titles = {"序列", "姓名", "电话", "楼宇", "面积", "人员同意状态"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet hssfSheet = workbook.createSheet("sheet1");
        CellRangeAddress region1 = new CellRangeAddress(0, 0, 0, 9);
        hssfSheet.addMergedRegion(region1);
        HSSFRow row1 = hssfSheet.createRow(0);
        row1.setHeight((short) 1400);
        HSSFCell cell = row1.createCell(0);//第二行第一列
        cell.setCellValue(SecondedName + time);
        HSSFRow row = hssfSheet.createRow(1);
        HSSFCellStyle hssfCellStyle = workbook.createCellStyle();
        HSSFCell hssfCell = null;
        for (int i = 0; i < titles.length; i++) {
            hssfCell = row.createCell(i);//列索引从0开始
            hssfCell.setCellValue(titles[i]);//列名
            hssfCell.setCellStyle(hssfCellStyle);//列居中显示
        }
        for (int i = 0; i < list.size(); i++) {
            row = hssfSheet.createRow(i + 2);
            //序号
            row.createCell(0).setCellValue(i + 1);
            //姓名
            row.createCell(1).setCellValue(list.get(i).getString("full_name"));
            //电话
            row.createCell(2).setCellValue(list.get(i).getString("telephone"));
            //楼宇
            row.createCell(3).setCellValue(list.get(i).getString("building_number"));
            //面积
            row.createCell(4).setCellValue(list.get(i).getString("housing_area"));
            row.createCell(5).setCellValue("同意");
//            //单位
//            row.createCell(5).setCellValue(list.get(i).getString("company"));
//            //民族
//            row.createCell(6).setCellValue(list.get(i).getString("user_nation"));
//            //政治面貌
//            row.createCell(7).setCellValue(list.get(i).getString("user_olitical_outlook"));
//            //个人宣言
//            row.createCell(8).setCellValue(list.get(i).getString("user_declaration"));
//            //  人员同意状态
//            Long agree_state = list.get(i).getLong("agree_state");
//            row.createCell(9).setCellValue("同意");
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.out.println(baos);
        workbook.write(baos);
        byte[] ba = baos.toByteArray();
        InputStream os = new ByteArrayInputStream(ba);
        String expName = SecondedName + time;
        String uploadExcelFile = OSSUtil.uploadExcelFile(os, expName);// kit! 为名称
        System.err.println(uploadExcelFile);
        os.close();
        return uploadExcelFile;
    }


}




